<template>
  <div class="app-container">
    <!-- 申请请假页面 -->
    <div v-if="currentStep === 1" class="leave-apply">
      <!-- 进度条 - 按照图片样式优化 -->
      <div class="progress-bar">
        <div class="progress-step" v-for="step in progressSteps" :key="step.id">
          <div class="step-circle" :class="{ active: currentStep >= step.id }">
            {{ step.id }}
          </div>
          <div class="step-text" :class="{ active: currentStep >= step.id }">
            {{ step.name }}
          </div>
        </div>
        <!-- 连接线 -->
        <div class="progress-line"></div>
      </div>
  
      <div class="form-container">
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <div class="form-grid">
            <div class="form-item">
              <label class="form-label required">老人姓名</label>
              <select 
                class="form-input"
                v-model="formData.elderId"
                @change="handleElderlyChange"
                :disabled="loading"
              >
                <option value="">请选择老人姓名</option>
                <option 
                  v-for="elderly in elderlyList" 
                  :key="elderly.id" 
                  :value="elderly.id"
                >
                  {{ elderly.name }}
                </option>
              </select>
              <div class="error-message" v-if="errors.elderName">{{ errors.elderName }}</div>
            </div>
            <div class="form-item">
              <label class="form-label">老人身份证号</label>
              <input 
                type="text" 
                class="form-input" 
                placeholder="身份证号"
                v-model="formData.elderIdCard"
                readonly
              >
            </div>
            <div class="form-item">
              <label class="form-label">联系方式</label>
              <input 
                type="text" 
                class="form-input" 
                placeholder="联系方式"
                v-model="formData.elderPhone"
                readonly
              >
            </div>
            <div class="form-item">
              <label class="form-label">入住床位</label>
              <input 
                type="text" 
                class="form-input" 
                placeholder="床位信息"
                v-model="formData.bedNumber"
                readonly
              >
            </div>
            <div class="form-item">
              <label class="form-label">护理员</label>
              <input 
                type="text" 
                class="form-input" 
                placeholder="请输入护理员姓名"
                v-model="formData.caregiver"
                @input="validateCaregiver"
                maxlength="20"
              >
              <div class="char-count">{{ formData.caregiver.length }}/20</div>
              <div class="error-message" v-if="errors.caregiver">{{ errors.caregiver }}</div>
            </div>
          </div>
        </div>
  
        <!-- 申请信息 -->
        <div class="form-section">
          <div class="section-title">申请信息</div>
          <div class="form-grid">
            <!-- 陪同人 -->
            <div class="form-item full-width">
              <label class="form-label required">陪同人</label>
              <div class="radio-group">
                <label class="radio-label" v-for="option in companionOptions" :key="option">
                  <input 
                    type="radio" 
                    name="companion" 
                    :value="option" 
                    v-model="formData.companion"
                    @change="handleCompanionChange"
                  > 
                  {{ option }}
                </label>
              </div>
              <div class="error-message" v-if="errors.companion">{{ errors.companion }}</div>
            </div>
  
            <!-- 陪同人姓名 -->
            <div class="form-item full-width" v-if="showCompanionFields">
              <label class="form-label required">陪同人姓名</label>
              <input 
                type="text" 
                class="form-input" 
                placeholder="请输入"
                v-model="formData.companionName"
                @input="validateCompanionName"
                maxlength="10"
              >
              <div class="char-count">{{ formData.companionName.length }}/10</div>
              <div class="error-message" v-if="errors.companionName">{{ errors.companionName }}</div>
            </div>
  
            <!-- 陪同人联系方式 -->
            <div class="form-item full-width" v-if="showCompanionFields">
              <label class="form-label required">陪同人联系方式</label>
              <input 
                type="text" 
                class="form-input" 
                placeholder="请输入"
                v-model="formData.companionPhone"
                @input="validateCompanionPhone"
                maxlength="11"
              >
              <div class="char-count">{{ formData.companionPhone.length }}/11</div>
              <div class="error-message" v-if="errors.companionPhone">{{ errors.companionPhone }}</div>
            </div>
  
            <!-- 请假周期 -->
            <div class="form-item full-width">
              <label class="form-label required">请假周期</label>
              <div class="date-inputs">
                <input 
                  type="datetime-local" 
                  class="form-input" 
                  v-model="formData.startDate"
                  :min="minStartDate"
                  @change="calculateLeaveDays"
                >
                <span class="date-separator">-</span>
                <input 
                  type="datetime-local" 
                  class="form-input" 
                  v-model="formData.endDate"
                  :min="formData.startDate"
                  @change="calculateLeaveDays"
                >
              </div>
              <div class="error-message" v-if="errors.date">{{ errors.date }}</div>
            </div>
  
            <!-- 请假天数 -->
            <div class="form-item">
              <label class="form-label">请假天数</label>
              <input type="text" class="form-input" readonly :value="formData.leaveDays + '天'">
            </div>
  
            <!-- 请假原因 -->
            <div class="form-item full-width">
              <label class="form-label required">请假原因</label>
              <textarea 
                class="form-input textarea" 
                placeholder="请输入" 
                rows="3"
                v-model="formData.leaveReason"
                @input="validateLeaveReason"
                maxlength="200"
              ></textarea>
              <div class="char-count">{{ formData.leaveReason.length }}/200</div>
              <div class="error-message" v-if="errors.leaveReason">{{ errors.leaveReason }}</div>
            </div>
          </div>
        </div>
  
        <!-- 按钮 -->
        <div class="form-buttons">
          <button type="button" class="btn btn-back" @click="handleBack">返回</button>
          <button type="button" class="btn btn-submit" @click="handleSubmit">提交</button>
        </div>
      </div>
    </div>
  
    <!-- 申请审批页面 -->
    <div v-else-if="currentStep === 2" class="approval-page">
      <!-- 进度条 - 按照图片样式优化 -->
      <div class="progress-bar">
        <div class="progress-step" v-for="step in progressSteps" :key="step.id">
          <div class="step-circle" :class="{ active: currentStep >= step.id }">
            {{ step.id }}
          </div>
          <div class="step-text" :class="{ active: currentStep >= step.id }">
            {{ step.name }}
          </div>
        </div>
        <!-- 连接线 -->
        <div class="progress-line"></div>
      </div>
  
      <div class="approval-container">
        <div class="approval-layout">
          <!-- 左侧：基本信息 + 申请信息 -->
          <div class="left-panel">
            <!-- 基本信息 -->
            <div class="info-section">
              <div class="section-title">基本信息</div>
              <div class="info-grid">
                <div class="info-item">
                  <label class="info-label">老人姓名</label>
                  <div class="info-value">{{ formData.elderName }}</div>
                </div>
                <div class="info-item">
                  <label class="info-label">老人身份证号</label>
                  <div class="info-value">{{ formData.elderIdCard }}</div>
                </div>
                <div class="info-item">
                  <label class="info-label">联系方式</label>
                  <div class="info-value">{{ formData.elderPhone }}</div>
                </div>

                <div class="info-item">
                  <label class="info-label">入住床位</label>
                  <div class="info-value">{{ formData.bedNumber }}</div>
                </div>
                <div class="info-item">
                  <label class="info-label">护理员</label>
                  <div class="info-value">{{ formData.caregiver }}</div>
                </div>
              </div>
            </div>
  
            <!-- 申请信息 -->
            <div class="info-section">
              <div class="section-title">申请信息</div>
              <div class="info-grid">
                <div class="info-item full-width">
                  <label class="info-label">陪同人</label>
                  <div class="info-value">{{ formData.companion }}</div>
                </div>
                <div v-if="showCompanionFields" class="info-item full-width">
                  <label class="info-label">陪同人姓名</label>
                  <div class="info-value">{{ formData.companionName }}</div>
                </div>
                <div v-if="showCompanionFields" class="info-item full-width">
                  <label class="info-label">陪同人联系方式</label>
                  <div class="info-value">{{ formData.companionPhone }}</div>
                </div>
                <div class="info-item full-width">
                  <label class="info-label">请假周期</label>
                  <div class="info-value">{{ formatDateRange(formData.startDate, formData.endDate) }}</div>
                </div>
                <div class="info-item">
                  <label class="info-label">请假天数</label>
                  <div class="info-value">{{ formData.leaveDays }}天</div>
                </div>
                <div class="info-item full-width">
                  <label class="info-label">请假原因</label>
                  <div class="info-value">{{ formData.leaveReason }}</div>
                </div>
              </div>
            </div>
          </div>
  
          <!-- 右侧：审批结果 + 操作记录 -->
          <div class="right-panel">
            <!-- 审批结果 -->
            <div class="approval-section">
              <div class="section-title">审批结果</div>
              <div class="approval-form">
                <div class="form-item full-width">
                  <label class="form-label required">审批结果</label>
                  <div class="radio-group vertical">
                    <label class="radio-label" v-for="result in approvalResults" :key="result.value">
                      <input 
                        type="radio" 
                        name="approvalResult" 
                        :value="result.value" 
                        v-model="approvalData.result"
                      > 
                      {{ result.label }}
                    </label>
                  </div>
                  <div class="error-message" v-if="approvalErrors.result">{{ approvalErrors.result }}</div>
                </div>
  
                <div class="form-item full-width">
                  <label class="form-label required">审批意见</label>
                  <textarea 
                    class="form-input textarea" 
                    placeholder="请输入审批意见"
                    v-model="approvalData.opinion"
                    @input="validateApprovalOpinion"
                    maxlength="500"
                  ></textarea>
                  <div class="char-count">{{ approvalData.opinion.length }}/500</div>
                  <div class="error-message" v-if="approvalErrors.opinion">{{ approvalErrors.opinion }}</div>
                </div>
              </div>
            </div>
  
            <!-- 操作记录 -->
            <div class="record-section">
              <div class="section-title">操作记录</div>
              <div class="record-list">
                <div class="record-item">
                  <div class="record-action">提交申请</div>
                  <div class="record-user">申请人</div>
                  <div class="record-time">{{ formatTime(currentTime) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
  
        <!-- 按钮 -->
        <div class="approval-buttons">
          <button type="button" class="btn btn-back" @click="currentStep = 1">返回</button>
          <button type="button" class="btn btn-submit" @click="handleApprovalSubmit">提交审批</button>
        </div>
      </div>
    </div>
    
    <!-- 审批结果页面 -->
    <div v-else-if="currentStep === 3" class="approval-result-page">
      <!-- 进度条 - 按照图片样式优化 -->
      <div class="progress-bar">
        <div class="progress-step" v-for="step in progressSteps" :key="step.id">
          <div class="step-circle" :class="{ active: currentStep >= step.id }">
            {{ step.id }}
          </div>
          <div class="step-text" :class="{ active: currentStep >= step.id }">
            {{ step.name }}
          </div>
        </div>
        <!-- 连接线 -->
        <div class="progress-line"></div>
      </div>
      
      <div class="result-container">
        <div class="result-content">
          <!-- 审批状态 -->
          <div class="status-section">
            <!-- 审批拒绝：红色❌ -->
            <div class="status-icon status-icon-rejected" v-if="formData.leaveStatus === '拒绝'">
              <span class="exclamation-icon" style="color:#ff4d4f">✕</span>
            </div>
            <!-- 已完成：绿色✓ -->
            <div class="status-icon status-icon-success" v-else-if="formData.leaveStatus === '2'">
              <span class="exclamation-icon" style="color:#52c41a">✓</span>
            </div>
            <!-- 审批中：黄色! -->
            <div class="status-icon" v-else>
              <span class="exclamation-icon">!</span>
            </div>
            
            <!-- 状态标题 -->
            <div class="status-title">
              {{ formData.leaveStatus === '拒绝' ? '审批拒绝' : (formData.leaveStatus === '2' ? '已完成' : '审批中') }}
            </div>
            
            <!-- 状态提示 -->
            <div class="status-message">
              {{ 
                formData.leaveStatus === '拒绝' 
                  ? '很抱歉，您的请假申请未通过审批。如有疑问，请联系护理组组长。' 
                  : (formData.leaveStatus === '2' 
                      ? '该申请已审批完成。' 
                      : '稍等，请使用申请单正在审批中，若该申请单长时间未处理，请联系护理组组长！')
              }}
            </div>
          </div>
          
          <!-- 操作记录 -->
          <div class="record-section">
            <div class="section-title">操作记录</div>
            <div class="record-list timeline">
              <div class="timeline-item">
                <div class="timeline-dot green"></div>
                <div class="timeline-content">
                  <div class="timeline-action">发起申请-申请请假</div>
                  <div class="timeline-time">{{ formatDateTime(new Date()) }}</div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-dot green"></div>
                <div class="timeline-content">
                  <div class="timeline-action">护理员（已发起）</div>
                  <div class="timeline-time">{{ formatDateTime(new Date()) }}</div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-dot" :class="formData.leaveStatus === '拒绝' ? 'red' : (formData.leaveStatus === '2' ? 'green' : 'blue')"></div>
                <div class="timeline-content">
                  <div class="timeline-action">审批-申请审批</div>
                  <div class="timeline-subtitle">
                    {{ 
                      formData.leaveStatus === '拒绝' 
                        ? '护理组组长（已拒绝）' 
                        : (formData.leaveStatus === '2' ? '护理组组长（已完成）' : '护理组组长（审批中）')
                    }}
                  </div>
                  <div class="timeline-time">{{ formatDateTime(new Date()) }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 返回按钮 -->
          <div class="result-buttons">
            <button type="button" class="btn btn-back" @click="handleBack">返回</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  
  <script setup>
import { ref, reactive, computed, onMounted, nextTick, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { listElderly ,getElderly} from '@/api/system/elderly'
import { getBed } from '@/api/system/bed'
import { listBinding } from '@/api/system/binding'
import { addRequest, updateRequest, getRequest } from '@/api/system/request'
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/system/record"
// function handleAdd() {
//   approvalData.value.handleType=formData.value.id
//   approvalData.value.extraField1=formData.value.taskId
//   approvalData.value.bussniessId=formData.value.bussniessId
//     addRecord(approvalData.value).then(response => {
//       proxy.$modal.msgSuccess("新增成功")
//       open.value = false
//       getList()
//     })
//   }
  
  const router = useRouter()
  const route = useRoute()
  
  // 获取当前实例
  const { proxy } = getCurrentInstance() || {}
  
  // 响应式数据
  // 从路由参数中获取step，默认为1
  const currentStep = ref(parseInt(route.query.step) || 1) // 1: 申请请假, 2: 申请审批, 3: 审批结果
  const currentTime = ref(new Date())
  
  // 进度条配置 - 按照图片内容设置
  const progressSteps = computed(() => {
    return [
      { id: 1, name: '申请请假' },
      { id: 2, name: '申请审批' },
      { id: 3, name: '请假审批' }
    ]
  })


  // 表单数据
  const formData = reactive({
    id: '',
    taskId: '',
    pendingTaskId: '',
    elderId: '',
    elderName: '',
    elderIdCard:'',
    elderPhone: '',
    careLevel: '',
    bedNumber: '',
    caregiver: '',
    companion: '',
    companionName: '',
    companionPhone: '',
    startDate: '',
    endDate: '',
    leaveDays: 0,
    leaveReason: '',
    leaveStatus: '',
  })
  
  // 老人列表
  const elderlyList = ref([])
  const loading = ref(false)
  
  // 审批数据
  const approvalData = reactive({
    result: '',
    opinion: ''
  })
  
  // 错误信息
  const errors = reactive({
    elderName: '',
    elderIdCard: '',
    elderPhone: '',
    careLevel: '',
    bedNumber: '',
    caregiver: '',
    companion: '',
    companionName: '',
    companionPhone: '',
    date: '',
    leaveReason: ''
  })
  
  const approvalErrors = reactive({
    result: '',
    opinion: ''
  })
  
  // 陪同人选项
  const companionOptions = ['家属', '护理人员', '其他', '无']
  
  // 审批结果选项
  const approvalResults = [
    { value: 'approve', label: '审批通过' },
    { value: 'reject', label: '审批拒绝' },
    // { value: 'reject_back', label: '驳回' },
  ]
  
  // 计算属性
  const showCompanionFields = computed(() => {
    return formData.companion && formData.companion !== '无'
  })
  
  // 计算最小开始日期（今天）
  const minStartDate = computed(() => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day}T${hours}:${minutes}`
  })
  
  const loadElderlyList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
    };
    const response = await listElderly(params);
    if (response && response.rows) {
      elderlyList.value = response.rows.map(item => ({
        id: item.id,
        name: item.name,
      }));
      console.log('成功加载老人简易列表，共', elderlyList.value.length, '条记录');
    } else {
      elderlyList.value = [];
      console.log('老人列表数据结构异常:', response);
    }
  } catch (error) {
    console.error('加载老人列表失败', error);
    elderlyList.value = [];
  } finally {
    loading.value = false;
  }
};
  
// 获取床位信息的函数
const getBedInfo = async (bedId) => {
  try {
    if (!bedId) return null;
    
    // 尝试调用床位API获取详细信息
    const response = await getBed(bedId);
    return response.data || null;
  } catch (error) {
    console.error('获取床位信息失败:', error);
    return null;
  }
};

const handleElderlyChange = async (event) => {
  const elderId = event.target.value;
  if (!elderId) {
    formData.elderName = '';
    formData.elderIdCard = '';
    formData.elderPhone = '';
    formData.bedNumber = '';
    formData.caregiver = '';
    errors.elderName = '';
    errors.elderIdCard = '';
    errors.elderPhone = '';
    errors.bedNumber = '';
    errors.caregiver = '';
    return;
  }
  try {
    loading.value = true;
    const response = await getElderly(elderId);
    const Elderly = response.data;
    if (Elderly) {
      console.log('通过接口获取的老人信息:', Elderly);
      console.log(formData.value)

      
      formData.elderName = Elderly.name || '';
      formData.elderIdCard = Elderly.idCard || '';
      formData.elderPhone = Elderly.contact || '';
      
      // 处理床位信息的多种情况
      let bedNo = '';
      
      // 情况1: 如果嵌套的bed对象存在且有bedNo
      if (Elderly.bed && Elderly.bed.bedNo) {
        bedNo = Elderly.bed.bedNo;
      }
      // 情况2: 如果直接有bedNo字段
      else if (Elderly.bedNo) {
        bedNo = Elderly.bedNo;
      }
      // 情况3: 如果有bed_id或bedId，使用它调用bed API获取床位号
      else if (Elderly.bed_id || Elderly.bedId) {
        const bedId = Elderly.bed_id || Elderly.bedId;
        
        // 调用获取床位信息的函数
        const bedInfo = await getBedInfo(bedId);
        if (bedInfo && bedInfo.bedNo) {
          bedNo = bedInfo.bedNo;
        } else {
          console.warn('未获取到床位号，床ID:', bedId);
        }
      }
      
      // 设置床位号显示
      formData.bedNumber = bedNo ? `${bedNo}` : '未分配床位';
      
      // 通过 binding 表获取护理员信息
      try {
        const bindingResponse = await listBinding({ elderlyId: elderId });
        console.log('绑定信息查询结果:', bindingResponse);
        
        if (bindingResponse && bindingResponse.rows && bindingResponse.rows.length > 0) {
          // 获取第一条绑定记录
          const binding = bindingResponse.rows[0];
          
          // 优先使用 sysUser.nickName
          if (binding.sysUser && binding.sysUser.nickName) {
            formData.caregiver = binding.sysUser.nickName;
            console.log('获取到护理员昵称:', formData.caregiver);
          } else {
            formData.caregiver = '';
            console.log('绑定记录中没有找到护理员昵称');
          }
        } else {
          formData.caregiver = '';
          console.log('该老人没有绑定护理员');
        }
      } catch (bindingError) {
        console.warn('获取绑定护理员信息失败:', bindingError);
        formData.caregiver = '';
      }
      
      errors.elderName = '';
      errors.elderIdCard = '';
      errors.elderPhone = '';
      errors.bedNumber = '';
      errors.caregiver = '';
    } else {
      console.error('接口返回的老人信息为空，id:', elderId);
    }
  } catch (error) {
    console.error('获取老人信息失败', error);
    formData.elderName = '';
    formData.elderIdCard = '';
    formData.elderPhone = '';
    formData.bedNumber = '';
    formData.caregiver = '';
    errors.elderName = '获取老人信息失败，请重试';
  } finally {
    loading.value = false;
  }
};

  const validateIdCard = () => {
    // 从下拉选择的老人，身份证号已自动填充，不需要单独验证
    errors.elderIdCard = ''
  }
  
  const validateElderPhone = () => {
    // 从下拉选择的老人，手机号已自动填充，不需要单独验证
    errors.elderPhone = ''
  }
  
  const validateCareLevel = () => {
    if (!formData.careLevel) {
      errors.careLevel = '请选择护理等级'
    } else {
      errors.careLevel = ''
    }
  }
  
  const validateBedNumber = () => {
    // 从下拉选择的老人，床位信息已自动填充，不需要单独验证
    errors.bedNumber = ''
  }
  
  const validateCaregiver = () => {
    // 护理员姓名不再是必填项
    errors.caregiver = ''
  }
  
  const handleCompanionChange = () => {
    if (formData.companion === '无') {
      formData.companionName = ''
      formData.companionPhone = ''
      errors.companionName = ''
      errors.companionPhone = ''
    }
  }
  
  const validateCompanionName = () => {
    if (!showCompanionFields.value) return
    
    if (!formData.companionName.trim()) {
      errors.companionName = '请输入陪同人姓名'
    } else {
      errors.companionName = ''
    }
  }
  
  const validateCompanionPhone = () => {
    if (!showCompanionFields.value) return
    
    const phone = formData.companionPhone.trim()
    if (!phone) {
      errors.companionPhone = '请输入陪同人联系方式'
    } else if (!/^1[3-9]\d{9}$/.test(phone)) {
      errors.companionPhone = '手机号格式错误'
    } else {
      errors.companionPhone = ''
    }
  }
  
  const validateLeaveReason = () => {
    if (!formData.leaveReason.trim()) {
      errors.leaveReason = '请输入请假原因'
    } else {
      errors.leaveReason = ''
    }
  }
  
  const validateApprovalOpinion = () => {
    if (!approvalData.opinion.trim()) {
      approvalErrors.opinion = '请输入审批意见'
    } else {
      approvalErrors.opinion = ''
    }
  }
  // 格式化时间为 "YYYY-MM-DD HH:MM:SS" 格式
const formatDateTime = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
  
  const calculateLeaveDays = () => {
    if (!formData.startDate || !formData.endDate) {
      formData.leaveDays = 0
      return
    }
    
    const startDate = new Date(formData.startDate)
    const endDate = new Date(formData.endDate)
    const today = new Date()
    
    // 检查开始时间是否早于今天
    if (startDate < today) {
      errors.date = '开始时间不能早于当前时间'
      formData.leaveDays = 0
      return
    }
    
    if (startDate >= endDate) {
      errors.date = '结束时间必须晚于开始时间'
      formData.leaveDays = 0
      return
    }
    
    errors.date = ''
    
    const diffTime = endDate - startDate
    const diffDays = diffTime / (1000 * 60 * 60 * 24)
    
    let calculatedDays
    if (diffDays < 0.5) {
      calculatedDays = 0.5
    } else if (diffDays > 0.5 && diffDays < 1) {
      calculatedDays = 1
    } else {
      calculatedDays = Math.round(diffDays * 2) / 2
    }
    
    formData.leaveDays = calculatedDays
  }
  
  const formatDateRange = (start, end) => {
    if (!start || !end) return ''
    const startStr = new Date(start).toLocaleString()
    const endStr = new Date(end).toLocaleString()
    return `${startStr} - ${endStr}`
  }
  
  const formatTime = (date) => {
    return date.toLocaleString('zh-CN')
  }
  
  const validateElderName = () => {
  if (!formData.elderId) {
    errors.elderName = '请选择老人姓名';
  } else {
    errors.elderName = '';
  }
};
  const validateForm = () => {
    let isValid = true
    
    // 清除所有错误
    Object.keys(errors).forEach(key => errors[key] = '')
    
    // 验证必填字段
    validateElderName()
    validateIdCard()
    validateElderPhone()
    validateBedNumber()
    validateCaregiver()
    
    // 验证陪同人信息
    if (!formData.companion) {
      errors.companion = '请选择陪同人类型'
      isValid = false
    }
    
    if (showCompanionFields.value) {
      validateCompanionName()
      validateCompanionPhone()
    }
    
    // 验证日期
    if (!formData.startDate || !formData.endDate) {
      errors.date = '请选择完整的请假周期'
      isValid = false
    } else if (new Date(formData.startDate) >= new Date(formData.endDate)) {
      errors.date = '结束时间必须晚于开始时间'
      isValid = false
    }
    
    // 验证请假原因
    validateLeaveReason()
    
    // 最终检查所有错误字段
    Object.keys(errors).forEach(key => {
      if (errors[key]) {
        isValid = false
      }
    })
    
    // 添加调试信息
    console.log('表单验证结果:', isValid)
    console.log('错误信息:', errors)
    
    return isValid
  }
  
  const validateApprovalForm = () => {
    let isValid = true
    
    Object.keys(approvalErrors).forEach(key => approvalErrors[key] = '')
    
    if (!approvalData.result) {
      approvalErrors.result = '请选择审批结果'
      isValid = false
    }
    
    validateApprovalOpinion()
    
    if (approvalErrors.opinion) {
      isValid = false
    }
    
    return isValid
  }
  
  const handleSubmit = () => {
      if (validateForm()) {
        // 准备提交到数据库的数据
        const submitData = {
          elderlyId: formData.elderId,
          leaveStartTime: formData.startDate,
          expectedEndTime: formData.endDate,
          expectedLeaveDays: formData.leaveDays,
          leaveReason: formData.leaveReason,
          companionType: formData.companion,
          companionName: formData.companionName || null,
          companionPhone: formData.companionPhone || null,
          leaveStatus: '3' // 审批中状态
        }
        
        // 提交数据到数据库
        addRequest(submitData).then(response => {
          console.log('提交成功，返回数据:', response)
          
          // 尝试不同方式获取id
          if (response && (response.id || response.data?.id || response.requestId)) {
            formData.id = response.id || response.data?.id || response.requestId
            formData.id = response.data.id; // 保存主键ID到formData
            console.log('保存的ID:', formData.id)
          }
          
          if (proxy && proxy.$modal) {
            proxy.$modal.msgSuccess('申请提交成功！')
          } else {
            alert('申请提交成功！')
          }
          
          // 设置本地状态为审批中
          formData.leaveStatus = '3'
          
          // 跳转到审批结果页面（审批中）
          currentStep.value = 3
          currentTime.value = new Date()
        }).catch(error => {
          console.error('提交失败:', error)
          
          // 提取后端返回的错误信息
          let errorMsg = '提交失败，请重试'
          
          if (error?.response?.data?.msg) {
            // 优先使用后端返回的msg
            errorMsg = error.response.data.msg
          } else if (error?.message) {
            // 其次使用error.message
            errorMsg = error.message
          }
          
          console.log('错误提示:', errorMsg)
          
          if (proxy && proxy.$modal) {
            proxy.$modal.msgError(errorMsg)
          } else {
            alert(errorMsg)
          }
        })
      }
      
    }
   
  const handleApprovalSubmit = () => {
      console.log('开始审批提交，当前表单数据:', formData)
      console.log('审批数据:', approvalData)
      
      if (validateApprovalForm()) {
        console.log('表单验证通过')
        
        // 检查必要参数
        if (!formData.id) {
          console.error('缺少记录ID，无法更新状态')
          if (proxy && proxy.$modal) {
            proxy.$modal.msgError('缺少记录信息，无法更新状态')
          } else {
            alert('缺少记录信息，无法更新状态')
          }
          return
        }
        if (!formData.taskId) {
          console.error('缺少taskId，无法提交审批')
          if (proxy && proxy.$modal) {
            proxy.$modal.msgError('缺少任务信息，无法提交审批')
          } else {
            alert('缺少任务信息，无法提交审批')
          }
          return
        }
        if (!formData.pendingTaskId) {
          console.warn('未携带ptId，将无法回写待办状态')
        }
        
        // 先保存审批记录
        const recordData = {
          handleType: formData.pendingTaskId || undefined,
          extraField1: formData.taskId,
          bussniessId: formData.id,
          opinion: approvalData.opinion,
          // 后端使用auditStatus判断通过/拒绝：1通过，2拒绝
          auditStatus: approvalData.result === 'approve' ? 1 : 2
        }
        
        console.log('准备提交审批记录:', recordData)
        
        addRecord(recordData)
          .then((response) => {
            console.log('审批记录保存成功:', response)
            // 审批通过时，同步更新请假状态
            const updateData = {
              id: formData.id,
              leaveStatus: approvalData.result === 'approve' ? '2' : '拒绝'
            }
            console.log('准备更新请假状态:', updateData)
            return updateRequest(updateData)
          })
          .then((response) => {
            console.log('请假状态更新成功:', response)
            if (proxy && proxy.$modal) {
              proxy.$modal.msgSuccess('审批提交成功')
            }
            // 切到结果页或返回
            currentStep.value = 3
            formData.leaveStatus = approvalData.result === 'approve' ? '2' : '拒绝'
          })
          .catch((error) => {
            console.error('审批提交失败:', error)
            
            // 提取后端返回的错误信息
            let errorMsg = '审批提交失败，请重试'
            
            if (error?.response?.data?.msg) {
              // 优先使用后端返回的msg
              errorMsg = error.response.data.msg
            } else if (error?.response?.data?.message) {
              // 其次使用message字段
              errorMsg = error.response.data.message
            } else if (error?.message) {
              // 最后使用error.message
              errorMsg = error.message
            }
            
            console.log('审批错误提示:', errorMsg)
            
            if (proxy && proxy.$modal) {
              proxy.$modal.msgError(errorMsg)
            } else {
              alert(errorMsg)
            }
          })
      } else {
        console.log('表单验证失败')
      }
    }
  
  const handleBack = () => {
    if (confirm('确定要返回吗？未保存的数据将会丢失。')) {
      router.back()
    }
  }
  
  // 根据业务ID加载数据
  const loadDataById = async () => {
    const id = route.query.id
    if (id) {
      try {
        loading.value = true
        console.log('=== 开始加载请假数据 ===')
        console.log('业务ID:', id)
        console.log('路由参数 statusFromRecord:', route.query.statusFromRecord)
        
        const response = await getRequest(id)
        if (response && response.data) {
          const data = response.data
          // 填充表单数据
          formData.id = data.id || ''
          formData.elderId = data.elderlyId || ''
          
          // 如果有老人ID，获取老人详细信息
          if (data.elderlyId) {
            await handleElderlyChange({ target: { value: data.elderlyId } })
          }
          
          // 设置其他表单数据
          formData.startDate = data.leaveStartTime || ''
          formData.endDate = data.expectedEndTime || ''
          formData.leaveDays = data.expectedLeaveDays || 0
          formData.leaveReason = data.leaveReason || ''
          formData.companion = data.companionType || ''
          formData.companionName = data.companionName || ''
          formData.companionPhone = data.companionPhone || ''
          
          // 优先使用从审批记录传递过来的状态
          if (route.query.statusFromRecord) {
            formData.leaveStatus = String(route.query.statusFromRecord)
            console.log('>>> 使用审批记录传递的状态:', formData.leaveStatus)
          } else {
            formData.leaveStatus = data.leaveStatus || ''
            console.log('>>> 使用数据库查询的状态:', formData.leaveStatus)
          }
          
          console.log('已加载业务数据:', formData)
          console.log('=== 数据加载完成 ===')
        }
      } catch (error) {
        console.error('加载业务数据失败:', error)
        if (proxy && proxy.$modal) {
          proxy.$modal.msgError('加载数据失败，请重试')
        }
      } finally {
        loading.value = false
      }
    }
  }
  
  onMounted(() => {
    // 初始化时加载老人列表
    loadElderlyList()
    
    // 接收路由参数中的任务信息
    if (route.query.taskId) {
      formData.taskId = String(route.query.taskId)
      console.log('接收 taskId:', formData.taskId)
    }
    if (route.query.ptId) {
      formData.pendingTaskId = String(route.query.ptId)
      console.log('接收 待办ID(ptId):', formData.pendingTaskId)
    }
    
    // 如果有ID参数，加载相应数据
    loadDataById()
  })
  </script>
  
  <style scoped>
  /* 共用样式 - 移除或修改全屏样式 */
  .leave-apply, .approval-page {
    background: #f5f5f5;
    padding: 20px;
    border-radius: 8px;
  }
  
  /* 进度条样式 - 按照图片样式优化 */
  .progress-bar {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 40px;
    position: relative;
    max-width: 500px;
    margin-left: auto;
    margin-right: auto;
    padding: 0 20px;
  }
  
  .progress-line {
    position: absolute;
    top: 15px;
    left: 50px;
    right: 50px;
    height: 2px;
    background: #e8e8e8;
    z-index: 1;
  }
  
  .progress-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    z-index: 2;
    flex: 1;
  }
  
  .step-circle {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: #e8e8e8;
    color: #999;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    margin-bottom: 8px;
    border: 2px solid #e8e8e8;
    transition: all 0.3s ease;
  }
  
  .step-circle.active {
    background: #1890ff;
    color: white;
    border-color: #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
  }
  
  .step-text {
    font-size: 14px;
    color: #999;
    white-space: nowrap;
    font-weight: normal;
    transition: all 0.3s ease;
  }
  
  .step-text.active {
    color: #1890ff;
    font-weight: 600;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    padding-left: 8px;
    border-left: 4px solid #1890ff;
    color: #333;
  }
  
  .form-label, .info-label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }
  
  .required::after {
    content: '*';
    color: #ff4d4f;
    margin-left: 4px;
  }
  
  .form-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    font-size: 14px;
    background: white;
    transition: border-color 0.3s;
  }
  
  .form-input:focus {
    outline: none;
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  }
  
  .textarea {
    resize: vertical;
    min-height: 80px;
  }
  
  .char-count {
    font-size: 12px;
    color: #999;
    text-align: right;
    margin-top: 4px;
  }
  
  .error-message {
    color: #ff4d4f;
    font-size: 12px;
    margin-top: 4px;
    min-height: 16px;
  }
  
  .btn {
    padding: 10px 24px;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    min-width: 100px;
    transition: all 0.3s;
    font-weight: 500;
  }
  
  .btn-back {
    background: #f5f5f5;
    color: #333;
    border: 1px solid #d9d9d9;
  }
  
  .btn-submit {
    background: #1890ff;
    color: white;
  }
  
  .btn-back:hover {
    background: #e6f7ff;
    border-color: #1890ff;
    color: #1890ff;
  }
  
  .btn-submit:hover {
    background: #40a9ff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
  }
  
  /* 申请请假页面样式 */
  .form-container {
    background: white;
    border-radius: 8px;
    padding: 30px;
    max-width: 800px;
    margin: 0 auto;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .form-section {
    margin-bottom: 30px;
  }
  
  .form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
  }
  
  .form-item {
    margin-bottom: 20px;
  }
  
  .form-item.full-width {
    grid-column: 1 / -1;
  }
  
  .radio-group {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
  }
  
  .radio-group.vertical {
    flex-direction: column;
    gap: 10px;
  }
  
  .radio-label {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 14px;
  }
  
  .radio-label input {
    margin-right: 6px;
  }
  
  .date-inputs {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .date-separator {
    color: #999;
    flex-shrink: 0;
    font-weight: bold;
  }
  
  .form-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
  }
  
  /* 申请审批页面样式 */
  .approval-container {
    background: white;
    border-radius: 8px;
    padding: 30px;
    max-width: 1200px;
    margin: 0 auto;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .approval-layout {
    display: grid;
    grid-template-columns: 1fr 400px;
    gap: 30px;
  }
  
  .left-panel, .right-panel {
    display: flex;
    flex-direction: column;
    gap: 30px;
  }
  
  .info-section {
    background: #fafafa;
    border-radius: 6px;
    padding: 20px;
    border: 1px solid #f0f0f0;
  }
  
  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
  }
  
  .info-item {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }
  
  .info-item.full-width {
    grid-column: 1 / -1;
  }
  
  .info-value {
    font-size: 14px;
    color: #666;
    background: white;
    padding: 8px 12px;
    border-radius: 4px;
    border: 1px solid #e8e8e8;
    min-height: 36px;
    display: flex;
    align-items: center;
  }
  
  .approval-section {
    background: #fafafa;
    border-radius: 6px;
    padding: 20px;
    border: 1px solid #f0f0f0;
  }
  
  .record-section {
    background: #fafafa;
    border-radius: 6px;
    padding: 20px;
    border: 1px solid #f0f0f0;
  }
  
  .record-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .record-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background: white;
    border-radius: 4px;
    border: 1px solid #e8e8e8;
    transition: all 0.3s ease;
  }
  
  .record-item:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .record-action {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }
  
  .record-user {
    font-size: 12px;
    color: #666;
  }
  
  .record-time {
    font-size: 12px;
    color: #999;
  }
  
  .approval-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
  }
  
  /* 审批结果页面样式 */
  .approval-result-page {
    background: #f5f5f5;
    padding: 20px;
    border-radius: 8px;
  }
  
  .result-container {
    background: white;
    border-radius: 8px;
    padding: 30px;
    max-width: 800px;
    margin: 0 auto;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .result-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 40px;
  }
  
  .status-section {
    text-align: center;
    padding: 40px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
  }
  
  .status-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: #fffbe6;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px solid #ffeaa7;
  }
  
  /* 审批成功：绿色背景 */
  .status-icon-success {
    background: #f6ffed !important;
    border: 2px solid #b7eb8f !important;
  }
  
  /* 审批拒绝：红色背景 */
  .status-icon-rejected {
    background: #fff1f0 !important;
    border: 2px solid #ffa39e !important;
  }
  
  .exclamation-icon {
    font-size: 40px;
    color: #ffa940;
    font-weight: bold;
  }
  
  .status-title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }
  
  .status-message {
    font-size: 16px;
    color: #666;
    line-height: 1.6;
    max-width: 600px;
  }
  
  .record-section {
    width: 100%;
    background: #fafafa;
    border-radius: 6px;
    padding: 20px;
    border: 1px solid #f0f0f0;
  }
  
  .timeline {
    position: relative;
    padding-left: 30px;
  }
  
  .timeline::before {
    content: '';
    position: absolute;
    left: 15px;
    top: 20px;
    bottom: 0;
    width: 2px;
    background: #e8e8e8;
  }
  
  .timeline-item {
    position: relative;
    margin-bottom: 30px;
    padding-left: 20px;
  }
  
  .timeline-dot {
    position: absolute;
    left: -15px;
    top: 0;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    z-index: 1;
  }
  
  .timeline-dot.green {
    background: #52c41a;
  }
  
  .timeline-dot.blue {
    background: #1890ff;
  }
  
  .timeline-dot.red {
    background: #ff4d4f;
  }
  
  .timeline-content {
    background: white;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #e8e8e8;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }
  
  .timeline-action {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 5px;
  }
  
  .timeline-subtitle {
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
  }
  
  .timeline-time {
    font-size: 12px;
    color: #999;
  }
  
  .result-buttons {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .progress-bar {
      max-width: 100%;
      padding: 0 10px;
    }
    
    .progress-line {
      left: 30px;
      right: 30px;
    }
    
    .form-grid {
      grid-template-columns: 1fr;
    }
    
    .approval-layout {
      grid-template-columns: 1fr;
    }
    
    .info-grid {
      grid-template-columns: 1fr;
    }
    
    .record-item {
      flex-direction: column;
      gap: 8px;
      text-align: center;
    }
    
    .result-container {
      padding: 20px;
    }
    
    .status-icon {
      width: 60px;
      height: 60px;
    }
    
    .exclamation-icon {
      font-size: 30px;
    }
    
    .status-title {
      font-size: 20px;
    }
    
    .status-message {
      font-size: 14px;
    }
    
    .timeline {
      padding-left: 20px;
    }
    
    .timeline::before {
      left: 10px;
    }
    
    .timeline-item {
      padding-left: 15px;
    }
    
    .timeline-dot {
      left: -10px;
    }
  }
  </style>